<template>
  <el-table
    ref="ref-el-table"
    v-loading="loading"
    v-bind="props"
    v-on="events"
  >
    <el-table-column
      v-for="(item, index) in items"
      :key="buildDOMKey(item, index)"
      v-bind="item.props"
      v-on="item.events"
    />
  </el-table>
</template>

<script lang="ts">
/*
prop 列表
  CM: ComponentModel  组件模型
CM.meta 扩展
  addSelection: boolean 是否添加多选框 [默认为 true]
  addIndex: boolean     是否添加编号 [默认为 true]
ref 列表
  ref-el-table [默认]
*/
import { Component, Prop } from 'vue-property-decorator'
import TgComponent from '../TgComponent'
import { ComponentModel } from '@TG/interface'
import { isNotEmpty } from '@TG/kit/validate'

@Component({
  name: 'ElTablePackage'
})
export default class extends TgComponent {
  @Prop({ type: Object, required: true }) private CM!: ComponentModel
  @Prop({ type: Boolean, default: false }) private loading!: boolean

  get props() {
    return Object.assign(
      {
        stripe: true,
        border: true,
        fit: true,
        'highlight-current-row': true,
        style: 'width: 100%;'
      },
      this.CM.props,
      this.$attrs
    )
  }

  get events() {
    return Object.assign({}, this.CM.events, this.$listeners)
  }

  get items() {
    let addSelection = this.addSelection
    let addIndex = this.addIndex
    const items = this.CM.items || []
    if (isNotEmpty(items)) {
      items.forEach((item, index) => {
        const type = item.props?.type
        if (type && type.length) {
          if (addSelection && type === 'selection') {
            addSelection = false
          }
          if (addIndex && type === 'index') {
            addIndex = false
          }
        }
      })
      if (addIndex) {
        items.unshift({
          props: { type: 'index', fixed: 'left', width: '50' }
        })
      }
      if (addSelection) {
        items.unshift({
          props: { type: 'selection', align: 'center', fixed: 'left', width: '50' }
        })
      }
    }
    return items
  }

  get addSelection(): boolean {
    let addSelection = this.CM.meta?.addSelection
    if (addSelection === undefined) {
      addSelection = true
    }
    return addSelection
  }

  get addIndex(): boolean {
    let addIndex = this.CM.meta?.addIndex
    if (addIndex === undefined) {
      addIndex = true
    }
    return addIndex
  }

  public defaultRef() {
    return 'el-table'
  }
}
</script>
